import { ReloadOutlined } from '@ant-design/icons';
import { Empty, Button } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import { TaskCallResultInfo } from 'admin/schema/Task';
import { getCallResult } from 'admin/servers/servers';
import { getStore } from 'store/store';

interface CallResultProp {
  taskId: number;
}

const CallResult: React.FC<CallResultProp> = (prop: CallResultProp) => {
  const store = getStore();

  /** 强制触发重新渲染，没有别的业务意义 */
  const [trigger, setTrigger] = useState<boolean>(false);

  const [callResultData, setCallResultData] = useState<TaskCallResultInfo[]>([]);

  const [totalNum, setTotalNum] = useState<number>(0);

  store.addChangeEvent('currentTaskFinishedNum', val => {
    setTrigger(!trigger);
  });

  const refresh = useCallback((): void => {
    getCallResult(prop.taskId)
      .then(res => {
        const { data } = res;
        if (!data || !data.length) {
          return;
        }
        let total = 0;
        data.forEach(item => {
          total += parseInt(item.callValue);
        });
        setTotalNum(total);
        // 过滤为0的数据，找到"成功"的数据，排序在第一个。其他的数据降序排列
        let arr = data.filter((obj: any) => {
          return obj.callValue > 0;
        });
        if (!arr.length) {
          return;
        }
        const successResult: TaskCallResultInfo = arr.find(item => {
          return item.callStatus === '成功';
        }) as TaskCallResultInfo;
        const needPushSuccess = successResult && parseInt(successResult.callValue) !== 0;
        needPushSuccess && arr.splice(arr.indexOf(successResult), 1);
        arr.sort((a: any, b: any) => {
          return b.callValue - a.callValue;
        });
        needPushSuccess && arr.unshift(successResult);
        arr = arr.filter(item => item && item);
        setCallResultData(arr);
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }, [prop.taskId]);

  useEffect(() => {
    refresh();
  }, [refresh]);

  //保留n位小数
  function roundFun(value: any, n: any) {
    return Math.round(value * Math.pow(10, n)) / Math.pow(10, n);
  }
  // 百分比，显示XX.X%
  const getRate = (val: string): string => {
    const hadCallNum = totalNum || 0;
    const newVal = parseInt(val);
    if (!hadCallNum) {
      // 已呼数为0，短时间显示为--
      return '-- %';
    }
    return roundFun((newVal * 100) / hadCallNum, 1) + '%';
  };

  // 超过10000，显示XX.XX万
  const formatValue = (val: string): string => {
    const newVal = parseInt(val);
    return newVal >= 10000 ? (newVal / 10000).toFixed(2) + '万' : val;
  };

  return (
    <>
      {/* 刷新按钮 */}
      <Button className="refresh-btn" type="link" onClick={refresh}>
        <ReloadOutlined style={{ fontSize: 22 }} />
      </Button>
      {!callResultData.length && (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} imageStyle={{ height: 100 }} />
      )}
      {callResultData.length > 0 && (
        <div className="task-callresult-cellroom">
          {callResultData.map((item, index) => {
            return (
              <div className="callresult-cell" key={index}>
                <div className="callresult-cell-dataroom">
                  <span className="callresult-cell-value">{formatValue(item.callValue)}</span>
                  <span className="callresult-cell-rate">{getRate(item.callValue)}</span>
                </div>
                <div className="callresult-cell-desc">{item.callStatus}</div>
              </div>
            );
          })}
        </div>
      )}
    </>
  );
};

export default CallResult;
